<template>
  <div class="header-container">
    <div class="logo-container">
      <img src="../assets/logo.png" class="logo-img" alt="系统logo" />
      <div class="title-container">
        <span class="main-title">{{ userInfo.topConfiguration }}综合执法文书录入平台</span>
      </div>
    </div>

    <div class="right-section">
      <div class="user-info-container">
        <div class="head-class account-info">
          <span class="head-span-A">登录账号:</span>
          <span class="head-span">{{ user.account }}</span>
        </div>
        <div class="head-class user-name">
          <span class="head-span-A">当前用户:</span>
          <span class="head-span">{{ user.username }}</span>
        </div>
        <div class="head-class role-info">
          <span class="head-span-A">角色:</span>
          <span class="head-span">{{ user.roleName }}</span>
        </div>
        <div class="head-class unit-info" v-if="user.unitName">
          <span class="head-span-A">所属单位:</span>
          <span class="head-span">{{ user.unitName }}</span>
        </div>
      </div>
      <div class="operation-container">
        <el-dropdown trigger="click">
          <span class="dropdown-trigger">
            <span> | 切换用户</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu class="dropdown-menu">
              <el-dropdown-item v-for="(option, index) in options" :key="index" @click="selectOption(option)">
                {{ option.username }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <div class="logout-btn" @click="logout">
          <span> | 退出 </span>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="切换用户" width="30%" :before-close="handleClose">

    <el-form class="login-card" :model="loginForm" :rules="rules" ref="loginForm" label-width="25%"
      @keyup.enter.native="submitForm('loginForm')">
      <!-- 账户-->
      <el-form-item label="" class="yh" prop="account" style="width: 90%;padding-top: 8px;">
        <el-input v-model="loginForm.account" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <!-- 密码-->
      <el-form-item label="" class="mm" prop="password" style="width: 90%;padding-top: 4px">
        <el-input show-password v-model="loginForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <!--验证码-->
      <el-form-item label="" class="yz" prop="code" style="width: 90%">
        <el-input v-model="loginForm.code" class="code-input" placeholder="请输入验证码"
          style="width: 50%;float: left"></el-input>
        <span @click="refreshCode" style="padding-left: 35px">
          <s-identify :identifyCode="identifyCode"></s-identify>
        </span>
      </el-form-item>
      <!--登录按钮-->
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')" :disabled="!canSubmit" style="width: 65%">
          <h2>登 录</h2>
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import request from "@/utils/request";
import SIdentify from "@/views/SIdentify.vue";

export default {
  name: "Header",
  components: { SIdentify },
  data() {
    return {
      user: {},
      userInfo: {},
      options: ['Option 1', 'Option 2', 'Option 3'],
      dialogVisible: false,
      // 表单信息
      loginForm: {
        account: '',
        password: '',
        code: '',
      },
      identifyCodes: '1234567890',//随机串内容
      identifyCode: '',
      // 表单验证
      rules: {
        account: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  //页面初始化加载
  created() {
    let userStr = localStorage.getItem("user") || "{}"
    this.userInfo = JSON.parse(userStr)
    if (!userStr) {
      return
    }
    let userId = this.userInfo.id
    // 从后台取出更新后的最新用户信息
    request.get("/user/" + userId).then(res => {
      this.user = res.data
    })
    request.get("/user/findAllName").then(res => {
      if (res.code == '200') {
        this.options = res.data;
      }
    })
  },
  computed: {
    canSubmit() {
      const { account, password, code } = this.loginForm
      return Boolean(account && password && code)
    }
  },
  methods: {
    logout() {
      this.$confirm('是否确定退出系统?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem("user");
        localStorage.removeItem("documentNumber");
        this.$router.replace("/login")
        this.$message({ message: "退出登录", type: "info" });
      }).catch(() => {
      });
    },
    selectOption(selectedOption) {
      this.loginForm.account = selectedOption.account;
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
      this.dialogVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.loginForm.code.toLowerCase() !== this.identifyCode.toLowerCase()) {
            this.$message.error('请填写正确验证码')
            this.refreshCode()
            return
          }
          request.post("user/login", this.loginForm).then(res => {
            if (res.code == "200") {
              if (!res.data.menus || !res.data.menus.find(p => p.path === "home")) {
                this.$message.error("您没有权限访问，请联系管理员！")
                this.$router.replace("/login")
              } else {
                localStorage.setItem("user", JSON.stringify(res.data))
                request.get("unit/getAllUnitDocumentNumber").then(ures => {
                  if (ures.code == "200") {
                    this.$message({
                      type: "success",
                      message: "登录成功"
                    })
                    localStorage.setItem("documentNumber", JSON.stringify(ures.data))
                    this.$router.replace("/").then(() => {
                      window.location.reload();
                    })
                  }
                })
              }
            }
            else {
              this.$message.error('用户名或密码错误')
              return false;
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 刷新验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },

    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
      }
    },

    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
  }
}
</script>

<style scoped>
.header-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #409eff;
  border-bottom: 1px solid #e5e7eb;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-width: 320px;
  /* 确保在小屏幕上也有基本可用性 */
}

/* Logo区域 */
.logo-container {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  min-width: 0;
}

.logo-img {
  width: 40px;
  height: 40px;
  margin-right: 15px;
  border-radius: 4px;
  object-fit: contain;
  flex-shrink: 0;
}

.title-container {
  font-weight: 600;
  color: white;
  font-size: 26px;
  white-space: nowrap;
  min-width: 0;
}

.main-title {
  display: inline;
}

/* 右侧区域整体布局 */
.right-section {
  display: flex;
  align-items: center;
  flex: 0 1 auto;
  justify-content: flex-end;
  gap: 20px;
  min-width: 0;
}

/* 用户信息区域 */
.user-info-container {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 15px;
  color: #fff;
}

.head-class {
  font-size: 16px;
  white-space: nowrap;
}

.head-span-A {
  color: #ffffff;
  font-weight: 500;
  cursor: pointer;
}

.head-span {
  color: #d8d8d8;
  font-weight: 500;
  cursor: pointer;
  transition: color 0.2s;
}

.head-span:hover {
  color: #e6f7ff;
  text-decoration: underline;
}

/* 操作区域 */
.operation-container {
  display: flex;
  align-items: center;
  white-space: nowrap;
  flex-shrink: 0;
}

.dropdown-trigger {
  font-size: 16px;
  color: #e6f7ff;
  cursor: pointer;
  padding: 5px 8px;
  line-height: 40px;
  border-radius: 4px;
}

.dropdown-menu {
  max-height: 200px;
  width: 120px;
  overflow-y: auto;
}

.logout-btn {
  font-size: 17px;
  color: #e6f7ff;
  cursor: pointer;
  padding: 5px 8px;
  line-height: 40px;
  border-radius: 4px;
}

/* 响应式设计 - 逐步隐藏信息 */
@media screen and (max-width: 1500px) {
  .unit-info {
    display: none;
  }
}

@media screen and (max-width: 1300px) {
  .role-info {
    display: none;
  }
}

@media screen and (max-width: 1100px) {
  .user-name {
    display: none;
  }

  .title-container {
    font-size: 22px;
  }
}

@media screen and (max-width: 900px) {
  .account-info {
    display: none;
  }

  .user-info-container {
    display: none;
  }
}
</style>
